package com.stoney.http;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Stony on 2015/12/12.
 */
public class RequestQueue {

    private AtomicInteger sequenceGenerator = new AtomicInteger(1);
    private final PriorityBlockingQueue<Request> networkQueue = new PriorityBlockingQueue<Request>();

    private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;

    private BasicNetwork network;
    private NetworkDispatcher[] dispatchers;
    private ResponseDelivery delivery;
    public RequestQueue(BasicNetwork network) {
        this(network,DEFAULT_NETWORK_THREAD_POOL_SIZE);
    }

    public RequestQueue(BasicNetwork network, int poolSize) {
        this(network,poolSize,new ResponseDelivery());
    }
    public RequestQueue(BasicNetwork network, int threadPoolSize,ResponseDelivery delivery) {
        this.network = network;
        this.dispatchers = new NetworkDispatcher[threadPoolSize];
        this.delivery = delivery;
    }

    public void start() {
        for (int i = 0; i < dispatchers.length; i++) {
            NetworkDispatcher networkDispatcher = new NetworkDispatcher(networkQueue, network, delivery);
            dispatchers[i] = networkDispatcher;
            networkDispatcher.start();
        }
    }
    public void stop() {
        for (int i = 0; i < dispatchers.length; i++) {
            if (dispatchers[i] != null) {
                dispatchers[i].quit();
            }
        }
    }

    public Request add(Request request){
        networkQueue.add(request);
        request.setSequence(sequenceGenerator.get());
        sequenceGenerator.incrementAndGet();
        return request;
    }

    public void finish(Request request) {

    }
}
